#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import mie.frame as frame
import fcntl


def AppSingleton(pid_file, message=None):
    """Singleton for Application"""

    g = frame.frame(-1).f_globals

    fp = open(pid_file, "w")
    g["singleton_fp"] = fp
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
        print(message or "Another instance exist, quit now")
        os._exit(0)


class ClsSingleton(type):
    """ Singleton for Class

    add ```__metaclass__ = ClsSingleton``` to first line of class
    """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(ClsSingleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]
